<template>
  <div class="article-list" ref="article-list">
    <van-pull-refresh
      v-model="refreshLoading"
      @refresh="onRefresh"
      :success-text="refreshSuccessTip"
      success-duration="1000"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="onLoad"
      >
        <ArticleItem
          v-for="(article, index) in articles"
          :key="index"
          :article="article"
        />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from "@/api/article";
import ArticleItem from "@/components/article-item";

export default {
  name: "articleList",
  props: {
    channel: {
      type: Object,
      required: true,
    },
  },
  components: { ArticleItem },
  data() {
    return {
      articles: [], // 文章列表
      loading: false, // 控制loading状态
      finished: false, // 控制加载结束,为true时不再触发加载更多
      timestamp: "", // 文章列表的时间戳,用来请求更多的文章列表
      refreshLoading: false, // 下拉刷新loading状态
      refreshSuccessTip: "", // 刷新成功提示
      scrollTop: 0, // 记录滚动位置
    };
  },
  methods: {
    // 页面未铺满或滚动条触底时触发
    async onLoad() {
      const { data } = await getArticles({
        channel_id: this.channel.id,
        timestamp: this.timestamp || Date.now(),
      });
      const { results } = data.data;
      this.articles.push(...results);
      this.loading = false;

      if (results.length) this.timestamp = data.data.pre_timestamp;
      else this.finished = true;
    },
    // 下拉刷新的回调
    async onRefresh() {
      const { data } = await getArticles({
        channel_id: this.channel.id,
        timestamp: Date.now(),
      });

      const { results } = data.data;
      this.articles.unshift(...results);

      this.refreshLoading = false;

      this.refreshSuccessTip = `成功刷新了${results.length}条数据`;
    },
  },
  created() {
    this.$bus.$on("homeRouteLeave", () => {
      this.scrollTop = this.$refs["article-list"].scrollTop;
    });
  },
  activated() {
    this.$refs["article-list"].scrollTop = this.scrollTop;
  },
};
</script>

<style scoped lang="less">
.article-list {
  position: fixed;
  left: 0;
  right: 0;
  bottom: 50px;
  top: 105px;
  overflow-y: auto;
}
</style>
